package udes.assassin;

import java.util.List;

import udes.assassin.R;
import udes.assassin.server.api.DataStructure.LobbyInfo;
import udes.assassin.server.api.Message.Message;
import udes.assassin.server.api.Message.GameSelectionMessage.CreateLobbyMessage;
import udes.assassin.server.api.Message.GameSelectionMessage.JoinLobbyMessage;
import udes.assassin.server.api.Message.GameSelectionMessage.RefreshMessage;
import udes.assassin.server.api.Message.GameSelectionMessage.RefuseJoinMessage;
import udes.assassin.server.api.Message.LobbyMessage.LobbyEnteringMessage;
import udes.assassin.structure.Game;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class GameSelectionActivity extends ListActivity implements OnClickListener, MessageManager{

	public ArrayAdapter<Game> mAdapter;
	private String mSelectedGame;
	private AssassinApplication mAssassin;
	
	private Button mButtonCreateLobby;
	private Button mButtonRefresh;
	private Button mButtonJoinGame;
	private ApplyMessageTask mTask;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_selection);
        
        mAdapter = new GameListAdapter(this, Global.getInstance().mGameList);
        this.setListAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        
        mAssassin = (AssassinApplication) getApplication();
        mAssassin.mCurrentManager = this;
        
        mButtonCreateLobby = ((Button) findViewById(R.id.button_create_lobby));
        mButtonCreateLobby.setOnClickListener(this);
        mButtonRefresh = ((Button) findViewById(R.id.button_refresh_game_list));
        mButtonRefresh.setOnClickListener(this);
        mButtonJoinGame = ((Button) findViewById(R.id.button_game_selection_go_to_lobby));
        mButtonJoinGame.setOnClickListener(this);
      	
      	ListView lv = getListView();
      	 
        // listening to single list item on click
        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		mSelectedGame = (String) ((TextView) view.findViewById(R.id.game_server_name)).getText();
        		mButtonJoinGame.setEnabled(true);
        	}
        });
    }
    
    @Override 
    public void onResume(){
    	super.onResume();
    	
    	// On page load we will have a full game list
    	askRefreshGameList();
    	
    	mButtonCreateLobby.setEnabled(true);
    	mButtonJoinGame.setEnabled(false);
    	
    	if(mTask !=null){
    		mTask.stop();
    	}
    	mTask = new ApplyMessageTask(this, mAssassin);
        mTask.execute(1);
    }

    @Override
    public void onPause()
    {
		super.onPause();
    	mTask.stop();
    }
    
	public void onClick(View view) {
        Button clickedBtn = (Button) view;

        switch (clickedBtn.getId()) {
        	case R.id.button_create_lobby: 
        		// Create game
        		mAssassin.sendMessage(new CreateLobbyMessage());
        		mButtonCreateLobby.setEnabled(false);
        		mButtonJoinGame.setEnabled(false);
                break;

        	case R.id.button_refresh_game_list: 
        		askRefreshGameList();
        		break;
 
        	case R.id.button_game_selection_go_to_lobby:
        		// Joint game
            	Log.d("GameSelection", "Joining :: " + mSelectedGame);
        		mAssassin.sendMessage(new JoinLobbyMessage(mSelectedGame));
        		mButtonCreateLobby.setEnabled(false);
        		mButtonJoinGame.setEnabled(false);
        		break;
        }
    }
	
	private void askRefreshGameList(){
		clearListViewSelection();
		mButtonRefresh.setEnabled(false);
		mAssassin.sendMessage(new RefreshMessage(null));
	}
    
    private void clearListViewSelection(){
    	mSelectedGame = "";
		ListView lv = getListView();
		lv.clearFocus();
		lv.clearChoices();
		lv.clearAnimation();
    }
    
    private void updateGameList(List<LobbyInfo> aUpdatedList){
    	Global.getInstance().mGameList.clear();
		for ( LobbyInfo lobby : aUpdatedList) {
			Global.getInstance().mGameList.add(new Game(lobby));
		}
     
        mAdapter = new GameListAdapter(this, Global.getInstance().mGameList);
        setListAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }
    
    private void displayRefuseJoin(){
    	final Toast tag = Toast.makeText(getApplicationContext(), R.string.error_refuse_join, Toast.LENGTH_SHORT);
  		tag.show();
  		// This act as displaying a long toast
  		new CountDownTimer(4000, 1000){
  		    public void onTick(long millisUntilFinished) {tag.show();}
  		    public void onFinish() {tag.show();}
  		}.start();
    }

	public boolean manage(Message aMessage) {
    	Log.d("GameSelection", "Received a message :: " + aMessage.getClass().getSimpleName());
		
		if(aMessage.getClass().equals(RefreshMessage.class)) {
			RefreshMessage casted = (RefreshMessage)aMessage;
			updateGameList(casted.roomList);
	    	mButtonRefresh.setEnabled(true);
			return true;
		}
		else if(aMessage.getClass().equals(RefuseJoinMessage.class)) {
			RefuseJoinMessage casted = (RefuseJoinMessage)aMessage;
			updateGameList(casted.roomList);
	    	mButtonRefresh.setEnabled(true);
	    	displayRefuseJoin();
	    	return true;
		}
		else if(aMessage.getClass().equals(LobbyEnteringMessage.class)) {
			LobbyEnteringMessage casted = (LobbyEnteringMessage)aMessage;
			
			Global.getInstance().mGame = new Game(casted.info);
			Global.getInstance().mIsGameOwner = Global.getInstance().mGame.getName().contains(Global.getInstance().mId);
	    	mButtonRefresh.setEnabled(true);
	    	mTask.stop();
	    	startActivity(new Intent(this, LobbyActivity.class));
			return true;
		}
		
		return false;
	}
}
